package mianshi.metaapp;

import java.util.LinkedList;
import java.util.Queue;

// 约瑟夫问题
public class T1 {

    public static void main(String[] args) {
        int[] nums = {3, 1, 2, 5, 8, 6, 7, 89};
        int index = 0;
        int count = 0;
        int length = nums.length;
        boolean[] flag = new boolean[length];
        int leftCount = nums.length;// 剩余人数
        while (leftCount > 1) {
            if (!flag[index]) {
                count++;
                if (count == 5) {
                    count = 0;
                    flag[index] = true;
                    leftCount--;
                }
            }
            index++;
            if (index == length) {
                index = 0;
            }
        }
        for (int i = 0; i < nums.length; i++) {
            if (!flag[i]) {
                System.out.println(nums[i]);
            }
        }
        System.out.println("====================");
        System.out.println(t1(nums));
    }

    // 可以用队列来操作
    public static int t1(int[] nums) {
        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < nums.length; i++) {
            queue.offer(nums[i]);
        }
        int t = 1, res = -1;
        while (!queue.isEmpty()) {
            res = queue.poll();
            if (t == 5) {
                t = 1;
                continue;
            } else {
                queue.offer(res);
            }

            t++;

            if (queue.size() == 1) {
                break;
            }
        }
        return res;
    }
}
